package stud.mpgame.server;

import org.apache.mina.core.session.IoSession;
import stud.mpgame.network.ISessionListener;
import stud.mpgame.network.NetworkMonitor;

import stud.mpgame.network.service.ping.PingService;

/**
 * @author f.pavel91@gmail.com
 * @version 1.0
 */
public class PingAnalyzer {

    private NetworkMonitor networkMonitor;
    private PingService pingService;

    public PingAnalyzer(NetworkMonitor networkMonitor) {
        this.networkMonitor = networkMonitor;

        int pingDelay = ServerConfiguration.getInstance().getPingDelay();
        int pingStabilizationTime = ServerConfiguration.getInstance().getPingStabilizationTime();
        this.pingService = new PingService(networkMonitor, pingDelay, pingStabilizationTime, true);

        addSessionListener();
    }


    private void addSessionListener() {
        networkMonitor.addSessionListener(
                new ISessionListener() {
                    public void sessionOpened(IoSession session) {
                        pingService.addSession(session);
                    }

                    public void sessionClosed(IoSession session) {
                        pingService.removeSession(session);
                    }
                }
        );
    }

    public int getPing(IoSession session) {
        return pingService.getPing(session);
    }

}
